

package tomkitty;

import java.util.*;
import java.io.*;

/**
 *
 * Main class. Entry point of the server.
 *
 * Based on the example:
 * http://java.sun.com/developer/technicalArticles/Networking/Webserver/
 *
 * @author alan, micha
 *
 */
public class Main {
    
    public static final String version = "0.0.1";
    public static final String name = "Tomkitty";
    private static TkConfiguration conf;

    private void printHelp() {
      Debug.p("");
      Debug.p("Usage: java -jar tomkitty.jar [OPTIONS]");
      Debug.p("");
      Debug.p("OPTIONS are as follows:");
      Debug.p("    -h               this help message");
      Debug.p("    -o [key=value]   set a config option");
      Debug.p("    -s               show config options and quit");
      Debug.p("");
    }

    private void setConfigDefaults(Configuration conf) {
      conf.set("debug", "true")
          .set("port", "8080")
          .set("minthreads", "10")
          .set("maxthreads", "100")
          .set("docroot", "./javadocs")
          .set("classpath", "./appdist")
          .set("default_file", "index.html")
          .set("default_app", "system")
          .set("list_hidden_files", "false")
          .set("tomkitty_config", "./etc/tomkitty.conf")
          .set("vhost_config", "./etc/vhost.conf")
          .set("auth_config", "./etc/auth.conf");
    }

    private void parseCommandLine(String[] argv) {
      for(int i = 0; i < argv.length; i++) {
        String allowedOptions = "hos";
        if (argv[i].charAt(0) != '-' || argv[i].length() != 2 ||
            allowedOptions.indexOf(argv[i].charAt(1)) < 0) {
          Debug.e("tomkitty: bad option: " + argv[i]);
          printHelp();
          System.exit(1);
        }
        switch(argv[i].charAt(1)) {
          case 'h':
            printHelp();
            System.exit(0);
            break;
          case 'o':
            String arg;
            if (argv.length > i + 1) {
              arg = argv[i + 1];
              String[] tmp = arg.split("=", 2);
              if (tmp.length == 2) {
                conf.set(tmp[0].trim(), tmp[1].trim());
              } else {
                Debug.e("tomkitty: bad argument: '" + arg + "' (expected KEY=VALUE)");
                printHelp();
                System.exit(1);
              }
              i++;
            } else {
              Debug.e("tomkitty: missing parameter: " + argv[i]);
              printHelp();
              System.exit(1);
            }
            break;
          case 's':
            conf.list(System.out);
            Debug.p("");
            System.exit(0);
            break;
        }
      }
    }

    /** Creates a new instance of Main */
    public Main(String[] argv) {
      Debug.p("");
      Debug.p(name + "/" + version + " - it puts the turdlet in the kitty");
      Debug.p("");

      conf = new TkConfiguration();
      setConfigDefaults(conf);

      parseCommandLine(argv); // parse once just to get the 'config_file'
      conf.loadConfFromXML(conf.get("tomkitty_config"));

      parseCommandLine(argv); // parse again to override config file settings

      Debug.p("Loading configuration:");
      conf.list(System.out);
      Debug.p("");

      Debug.isEnabled((conf.get("debug").toLowerCase().equals("true")));

      AppContext ac = new TkAppContext();
      ac.setConfig(conf);

      Handler et = (new TkErrorTurdlet()).init(null, ac);
      Handler tf = (new TkTurdletFactory()).init(et, ac);
      Handler sh = (new TkStaticHandler()).init(tf, ac);
      Handler am = (new TkAppManager()).init(sh, ac);
      Handler ah = (new TkAuthenticationHandler()).init(am, ac);
      Handler vh = (new TkVHostHandler()).init(ah, ac);
      Handler hh = (new TkHttpHandler()).init(vh, ac);
      Handler ch = (new TkConnectionHandler()).init(hh, ac);
      Handler ss = (new TkServer()).init(ch, ac);

      Debug.p("\nAll systems go.\n");
    }

    /**
     * Instantiate and kick things off.
     * @param argv the command line arguments
     */
    public static void main(String[] argv) {
        new Main(argv);
    }
}
